package top.likeqc.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.likeqc.common.lang.Result;
import top.likeqc.controller.easyexcel.UploadDAO;
import top.likeqc.controller.easyexcel.UploadData;
import top.likeqc.controller.easyexcel.TeacherUploadDataListener;
import top.likeqc.entity.SysUser;
import top.likeqc.entity.Teacher;
import top.likeqc.service.ITeacherService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author likeqc
 * @since 2022-04-09
 */
@RestController
@RequestMapping("/teacher")
public class TeacherController extends BaseController {
    @Autowired
    ITeacherService teacherService;

    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private UploadDAO uploadDAO;


    @GetMapping("/list")
    // @PreAuthorize("hasAuthority('sys:user:list')")
    public Result list(String name) {
        Page<Teacher> pageData = teacherService.page(getPage(),
            new QueryWrapper<Teacher>().like(StringUtils.isNotBlank(name), "name", name));

        return Result.success(pageData);
    }

    /**
     * 新增、修改 教师
     *
     * @param teacher
     * @return
     */
    @PostMapping("/edit")
    // @PreAuthorize("hasAuthority('sys:user:save')")
    @Transactional
    public Result edit(@Validated @RequestBody Teacher teacher) {
        teacher = teacherService.edit(teacher);
        return Result.success(teacher);
    }

    @PostMapping("/delete")
    // @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result delete(@RequestBody Long[] userIds) {
        teacherService.delete(userIds);
        return Result.success("");
    }

    /**
     * 文件上传
     * <p>
     * 1. 创建excel对应的实体对象 参照{@link UploadData}
     * <p>
     * 2. 由于默认一行行的读取excel，所以需要创建excel一行一行的回调监听器，参照{@link TeacherUploadDataListener}
     * <p>
     * 3. 直接读即可
     */
    @PostMapping("/upload")
    @ResponseBody
    public Result upload(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Teacher.class, new TeacherUploadDataListener(teacherService)).sheet().doRead();
        return Result.success("");
    }
}
